package com.kailing.bootBatch.thread;

/**
 * <h3>partitionjob</h3>
 * <p>fb2</p>
 *
 * @author : hduong
 * @version : 1.0
 * @date : 2019-12-18 10:38
 **/
public class FooBar2 {
    private int n;
    private volatile boolean fooBarTurn = true;
    private Object lock = new Object();

    public FooBar2(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i ++) {
            synchronized (lock) {
                if (!fooBarTurn) {
                    lock.wait();
                }
                fooBarTurn = false;
                printFoo.run();
                lock.notifyAll();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        for (int j = 0; j < n; j ++) {
            synchronized (lock) {
                if(fooBarTurn) {
                    lock.wait();
                }
                fooBarTurn = true;
                printBar.run();
                lock.notifyAll();
            }
        }
    }
}
